package com.sinoatma.physignsmonitor.fragment

import android.annotation.SuppressLint
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.bigkoo.pickerview.view.WheelTime.dateFormat
import com.common.frame.base.BaseFragment
import com.common.frame.extension.setSingleClick
import com.common.frame.utils.Utils.encodeAsBitmap
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IFillFormatter
import com.github.mikephil.charting.formatter.ValueFormatter
import com.hjq.toast.ToastUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.journeyapps.barcodescanner.CaptureActivity
import com.scandecode.ScanDecode
import com.sinoatma.physignsmonitor.MyApp
import com.sinoatma.physignsmonitor.MyApp.Companion.excelService
import com.sinoatma.physignsmonitor.MyApp.Companion.scanDecode
import com.sinoatma.physignsmonitor.MyApp.Companion.stopMonitorFlag1
import com.sinoatma.physignsmonitor.MyApp.Companion.stopMonitorFlag2
import com.sinoatma.physignsmonitor.R
import com.sinoatma.physignsmonitor.adapter.BpBleAdapter
import com.sinoatma.physignsmonitor.bean.*
import com.sinoatma.physignsmonitor.constant.*
import com.sinoatma.physignsmonitor.constant.Constant.BPStartCmd
import com.sinoatma.physignsmonitor.constant.Constant.BPStopCmd
import com.sinoatma.physignsmonitor.constant.Constant.BPTestCmd
import com.sinoatma.physignsmonitor.constant.Constant.sopQueryCmd
import com.sinoatma.physignsmonitor.databinding.FragmentMonitorBinding
import com.sinoatma.physignsmonitor.utils.FileUtils
import com.sinoatma.physignsmonitor.view.DialogUploadFailedUtil
import com.sinoatma.physignsmonitor.view.DialogUploadInfoFailedUtil
import com.sinoatma.physignsmonitor.view.DialogUtil
import com.sinoatma.physignsmonitor.view.LoadProgressDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit


/**
 * 献血监控首页
 */
class MonitorFragment : BaseFragment<MonitorViewModel,FragmentMonitorBinding>() {
    override fun layoutId(): Int =R.layout.fragment_monitor
    var handler = Handler()
    lateinit var loadProgressDialog: LoadProgressDialog
    var maxVisibleDataPoints = 12
    lateinit var dateFormat: SimpleDateFormat
    lateinit var adapter1: BpBleAdapter
    lateinit var adapter2: BpBleAdapter

    var SPO1: Runnable = object : Runnable {
        override fun run() {
            if (viewModel.o2ringConnectStatus1==1){
                LiveEventBus.get("receiveCmd1", SendCmd::class.java).post(SendCmd(1, sopQueryCmd))
            }

            handler.postDelayed(this, 1000)
        }
    }
/*
    var bp: Runnable = object : Runnable {
        override fun run() {
            if (viewModel.bPConnectStatus1){
                LiveEventBus.get("receiveCmd2", SendCmd::class.java).post(SendCmd(1, BPTestCmd))
            }
            handler.postDelayed(this, 10000)
        }
    }
*/

    var SPO2: Runnable = object : Runnable {
        override fun run() {
            if (viewModel.o2ringConnectStatus2==1) {
                LiveEventBus.get("receiveCmdTwo1", SendCmd::class.java).post(SendCmd(1, sopQueryCmd))
            }

            handler.postDelayed(this, 1000)
        }
    }
/*    var bp2: Runnable = object : Runnable {
        override fun run() {
            if (viewModel.bPConnectStatus2){
                LiveEventBus.get("receiveCmdTwo2", SendCmd::class.java).post(SendCmd(1, BPTestCmd))
            }
            handler.postDelayed(this, 10000)
        }
    }*/


    override fun initData() {
        loadProgressDialog = LoadProgressDialog(requireActivity())
        scanDecode = ScanDecode(requireActivity())
        scanDecode.initService("true")
    }

    override fun initView() {
        dateFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
        initChart1()
        initChart2()
        if (viewModel.headList.size==0){
            viewModel.initHeadExcel()
        }
        adapter1=BpBleAdapter(viewModel.bpList1)
        adapter2=BpBleAdapter(viewModel.bpList2)
        binding.layoutMonitorInterface1.bpRecycler.layoutManager=LinearLayoutManager(requireActivity())
        binding.layoutMonitorInterface1.bpRecycler.adapter=adapter1
        binding.layoutMonitorInterface2.bpRecycler.layoutManager=LinearLayoutManager(requireActivity())
        binding.layoutMonitorInterface2.bpRecycler.adapter=adapter2
        binding.layoutMonitorInterface1.tvEarlyWarningDate.text=viewModel.sdfDate.format(Date())
        binding.layoutMonitorInterface2.tvEarlyWarningDate.text=viewModel.sdfDate.format(Date())
        handler.postDelayed(SPO1,2000)
        handler.postDelayed(SPO2,2000)


//        lifecycleScope.launch(Dispatchers.IO){
//            while (true){
//                delay(1000)
//                viewModel.commandStartCalculate()
//            }
//        }


    }
    
    @SuppressLint("SuspiciousIndentation")
    override fun initListener() {
        binding.layoutMonitorInterface1.tvScanCode.setSingleClick {
            viewModel.scanType=0
            startScan()
        }
        binding.layoutMonitorInterface2.tvScanCode.setSingleClick {
            viewModel.scanType=1
            startScan()
        }

        binding.layoutMonitorInterface1.personInfoLayout.setSingleClick {
            infoFillIn()
        }
        binding.layoutMonitorInterface2.personInfoLayout.setSingleClick {
            infoFillIn()
        }


        binding.layoutMonitorInterface1.scanCodeImg.setSingleClick {
            viewModel.scanType=0
            startScan()
        }

        binding.layoutMonitorInterface2.scanCodeImg.setSingleClick {
            viewModel.scanType=1
            startScan()
        }



        binding.layoutMonitorInterface1.tvMonitoringControl1.setSingleClick {
            if (binding.layoutMonitorInterface1.tvMonitoringControl1.text.toString()=="停止监测"){
                loadProgressDialog.showWithAutoClose("正在结束监测，数据整理中...",8)
                LiveEventBus.get("receiveCmd1",SendCmd::class.java).post(SendCmd(type = 2))
                viewModel.o2ringConnectStatus1=0
                binding.layoutMonitorInterface1.tvSpoConnectStatus.text="未连接 ${O2RingName}"
                viewModel.excelListDataTemp.addAll(viewModel.excelListData)
                lifecycleScope.launch(Dispatchers.IO){
                    viewModel.excelListData.clear()
//                    Log.e("zsy","现在这里有几个数据${viewModel.excelListDataTemp.size}")
                    excelService.bloodCollectExportExcel1(viewModel.excelListDataTemp, viewModel.headList, viewModel.filePath)
                    stopMonitorFlag1=1
                }
                if (ModeFlag==0){
                    loadProgressDialog.dismiss()
                    lifecycleScope.launch(Dispatchers.IO) {
                        Log.e("zsy","${viewModel.monitorCode1}")
                        viewModel.insertRecord(
                            MonitorRecordEntity(bloodDonationCode=viewModel.monitorCode1,
                                name=viewModel.monitorName1,sex=viewModel.monitorSex1,
                                warningTimes=viewModel.numberEarlyWarning1,dateStr=viewModel.sdfFile.format(Date()),
                                fileAddress=viewModel.filePath))
                        withContext(Dispatchers.Main){
                            MyApp.stopMonitorFlag1 =0
                            viewModel.filePath=""
                            viewModel.monitorCode1=""
                            viewModel.monitorName1=""
                            viewModel.monitorSex1=""
                            viewModel.monitorAge1=""
                            viewModel.numberEarlyWarning1=0
                            binding.layoutMonitorInterface1.scanCodeLayout.visibility=View.VISIBLE
                            binding.layoutMonitorInterface1.bloodDonationInfoLayout.visibility=View.GONE
                            binding.layoutMonitorInterface1.tvScanCodeNum.text=""
                            binding.layoutMonitorInterface1.tvPersonInfo.text="个人信息"
                            viewModel.bpList1.clear()
                            adapter1.notifyDataSetChanged()
                        }
                    }
                }
            }
            else
            {
                if (viewModel.monitorCode1.isEmpty()){
                    loadProgressDialog.showWithAutoClose("请先录入条码!",2)
                    return@setSingleClick
                }

                if (ModeFlag==1){
                    loadProgressDialog.setMessage("献血信息上传...")
                    viewModel.uploadInfo(1)
                }else{
                    if (viewModel.o2ringConnectStatus1==0){
                        loadProgressDialog.setMessage("血氧设备${O2RingMac}连接中...")
                        lifecycleScope.launch(Dispatchers.IO){
                            viewModel.initExcelFolder("${viewModel.monitorName1}","${viewModel.monitorCode1}")
                        }
                        LiveEventBus.get("receiveCmd1",SendCmd::class.java).post(SendCmd(type = 3, cmd = O2RingMac))
                    }else{
                        lifecycleScope.launch(Dispatchers.IO){
                            viewModel.initExcelFolder("${viewModel.monitorName1}","${viewModel.monitorCode1}")
                        }
                    }
                }
            }
        }

        binding.layoutMonitorInterface2.tvMonitoringControl1.setSingleClick {
            if (binding.layoutMonitorInterface2.tvMonitoringControl1.text.toString()=="停止监测"){
                loadProgressDialog.showWithAutoClose("正在结束监测，数据整理中...",8)
                LiveEventBus.get("receiveCmdTwo1",SendCmd::class.java).post(SendCmd(type = 2))
                viewModel.o2ringConnectStatus2=0
                binding.layoutMonitorInterface2.tvSpoConnectStatus.text="未连接 ${O2RingNameRight}"

                viewModel.excelListDataTempTwo.addAll(viewModel.excelListDataTwo)
                lifecycleScope.launch(Dispatchers.IO){
                    viewModel.excelListDataTwo.clear()
                    Log.e("zsy","现在这里有几个数据${viewModel.excelListDataTempTwo.size}")
                    excelService.bloodCollectExportExcel2(viewModel.excelListDataTempTwo, viewModel.headList, viewModel.filePathTwo)
                    stopMonitorFlag2=1
                }
                 if (ModeFlag==0){
                     lifecycleScope.launch(Dispatchers.IO) {
                         Log.e("zsy","${viewModel.monitorCode2}")
                         viewModel.insertRecord(
                             MonitorRecordEntity(bloodDonationCode=viewModel.monitorCode2,
                                 name=viewModel.monitorName2,sex=viewModel.monitorSex2,
                                 warningTimes=viewModel.numberEarlyWarning2,
                                 dateStr=viewModel.sdfFile.format(Date()),
                                 fileAddress=viewModel.filePathTwo))
                         withContext(Dispatchers.Main){
                             stopMonitorFlag2=0
                             viewModel.filePathTwo=""
                             viewModel.monitorCode2=""
                             viewModel.monitorName2=""
                             viewModel.monitorSex2=""
                             viewModel.monitorAge2=""
                             viewModel.numberEarlyWarning2=0
                             binding.layoutMonitorInterface2.scanCodeLayout.visibility=View.VISIBLE
                             binding.layoutMonitorInterface2.bloodDonationInfoLayout.visibility=View.GONE
                             binding.layoutMonitorInterface2.tvScanCodeNum.text=""
                             binding.layoutMonitorInterface2.tvPersonInfo.text="个人信息"
                             viewModel.bpList2.clear()
                             adapter2.notifyDataSetChanged()
                         }
                     }
                 }
            }else{
                if (viewModel.monitorCode2.isEmpty()){
                    loadProgressDialog.showWithAutoClose("请先录入条码!",2)
                    return@setSingleClick
                }
                if (ModeFlag==1){
                    loadProgressDialog.setMessage("献血信息上传...")
                    viewModel.uploadInfo(2)
                }else{
                    if (viewModel.o2ringConnectStatus2==0){
                        loadProgressDialog.setMessage("血氧设备${O2RingMacRight}连接中...")
                        lifecycleScope.launch(Dispatchers.IO){
                            viewModel.initExcelFolder2("${viewModel.monitorName2}","${viewModel.monitorCode2}")
                        }
                        LiveEventBus.get("receiveCmdTwo1",SendCmd::class.java).post(SendCmd(type = 3, cmd = O2RingMacRight))
                    }else{
                        lifecycleScope.launch(Dispatchers.IO){
                            viewModel.initExcelFolder2("${viewModel.monitorName2}","${viewModel.monitorCode2}")
                        }
                    }
                }
            }
        }
        
        binding.layoutMonitorInterface1.tvStartBp.setSingleClick {
            if (viewModel.monitorCode1.isEmpty()){
                loadProgressDialog.showWithAutoClose("请先录入条码!",2)
                return@setSingleClick
            }
            when (binding.layoutMonitorInterface1.tvStartBp.text) {
                "停止测量" -> {
                    LiveEventBus.get("receiveCmd2",SendCmd::class.java).postDelay(SendCmd(type = 1, cmd = BPStopCmd),500)
                    binding.layoutMonitorInterface1.tvStartBp.text="开始测量"
                }
                "开始测量" -> {
                    if (viewModel.bPConnectStatus1){
                        LiveEventBus.get("receiveCmd2",SendCmd::class.java).postDelay(SendCmd(type = 1, cmd = BPStartCmd),500)
                        binding.layoutMonitorInterface1.tvStartBp.text="停止测量"
                    }else{
                        Toast.makeText(requireActivity(),"请先打开血压计",Toast.LENGTH_SHORT).show()
                        loadProgressDialog.showWithAutoClose("血压设备连接中...",15)
                        LiveEventBus.get("receiveCmd2",SendCmd::class.java).post(SendCmd(type = 3, cmd = BPMac))
                    }
                }
            }

        }
        binding.layoutMonitorInterface2.tvStartBp.setSingleClick {
            if (viewModel.monitorCode2.isEmpty()){
                loadProgressDialog.showWithAutoClose("请先录入条码!",2)
                return@setSingleClick
            }
            when (binding.layoutMonitorInterface2.tvStartBp.text) {
                "停止测量" -> {
                    LiveEventBus.get("receiveCmdTwo2",SendCmd::class.java).postDelay(SendCmd(type = 1, cmd = BPStopCmd),500)
                    binding.layoutMonitorInterface2.tvStartBp.text="开始测量"
                }
                "开始测量" -> {
                    if (viewModel.bPConnectStatus2){
                        LiveEventBus.get("receiveCmdTwo2",SendCmd::class.java).postDelay(SendCmd(type = 1, cmd = BPStartCmd),500)
                        binding.layoutMonitorInterface2.tvStartBp.text="停止测量"
                    }else{
                        Toast.makeText(requireActivity(),"请先打开血压计",Toast.LENGTH_SHORT).show()
                        loadProgressDialog.showWithAutoClose("血压设备连接中...",15)
                        LiveEventBus.get("receiveCmdTwo2",SendCmd::class.java).post(SendCmd(type = 3, cmd = BPMacRight))
                    }
                }
            }
        }

    }


    override fun initObserve() {
        LiveEventBus.get("upFile",Int::class.java).observe(this, androidx.lifecycle.Observer {
            if (it==1){
                stopMonitorFlag1=0
                val excelFile = File(viewModel.filePath)
                Log.e("zsy","数据已成功导出到Excel文件 ${excelFile.length()}")
                if (excelFile.exists()) {
                    Log.e("zsy","文件是否存在=${excelFile.exists()}")
                    viewModel.uploadFile(excelFile,1)
                }
                viewModel.excelListDataTemp.clear()
                binding.layoutMonitorInterface1.tvMonitoringControl1.text="开始监测"
            }

            if (it==2){
                stopMonitorFlag2=0
                val excelFile = File(viewModel.filePathTwo)
                Log.e("zsy","数据已成功导出到Excel文件 ${excelFile.length()}")
                if (excelFile.exists()) {
                    Log.e("zsy","文件是否存在=${excelFile.exists()}")
                    viewModel.uploadFile(excelFile,2)
                }
                viewModel.excelListDataTempTwo.clear()
                binding.layoutMonitorInterface2.tvMonitoringControl1.text="开始监测"
            }
        })

        viewModel.uploadInfo.observe(this, androidx.lifecycle.Observer {
            loadProgressDialog.dismiss()
            if (it=="信息上传成功"){
                if (viewModel.upInfo==1){
                    if (viewModel.o2ringConnectStatus1==0){
                        loadProgressDialog.setMessage("血氧设备${O2RingMac}连接中...")
                        lifecycleScope.launch{
                            withContext(Dispatchers.IO) {
                                viewModel.initExcelFolder("${viewModel.monitorName1}","${viewModel.monitorCode1}")
                            }
//                            viewModel.initExcelFolder("${viewModel.monitorName1}","${viewModel.monitorCode1}")
                            LiveEventBus.get("receiveCmd1",SendCmd::class.java).post(SendCmd(type = 3, cmd = O2RingMac))
                        }

                    }else{
                        lifecycleScope.launch(Dispatchers.IO){
                            viewModel.initExcelFolder("${viewModel.monitorName1}","${viewModel.monitorCode1}")
                        }
                    }
                }else{
                    if (viewModel.o2ringConnectStatus2==0){
                        loadProgressDialog.setMessage("血氧设备${O2RingMacRight}连接中...")
                        lifecycleScope.launch{
                            withContext(Dispatchers.IO) {
                                viewModel.initExcelFolder2("${viewModel.monitorName2}","${viewModel.monitorCode2}")
                            }
                            LiveEventBus.get("receiveCmdTwo1",SendCmd::class.java).post(SendCmd(type = 3, cmd = O2RingMacRight))
                        }
                    }else{
                        lifecycleScope.launch(Dispatchers.IO){
                            viewModel.initExcelFolder2("${viewModel.monitorName2}","${viewModel.monitorCode2}")
                        }
                    }
                }
            }else{
                DialogUploadInfoFailedUtil.showCustomDialogWithCountdown(
                        requireActivity(),
                    DialogUploadInfoFailedUtil.DialogType.INFO,it,
                        onPositiveButtonClick = {
                            // 确定按钮点击事件的逻辑
                            if (viewModel.upInfo==1){
                                loadProgressDialog.setMessage("献血信息上传...")
                                viewModel.uploadInfo(1)
                            }

                            if (viewModel.upInfo==2){
                                loadProgressDialog.setMessage("献血信息上传...")
                                viewModel.uploadInfo(2)
                            }
                        },
                        onNegativeButtonClick = {
                            // 取消按钮点击事件的逻辑
                            if (viewModel.upInfo==1){
                                stopMonitorFlag1=0
                                viewModel.excelId1=""
                                viewModel.filePath=""
                                viewModel.monitorCode1=""
                                viewModel.monitorName1=""
                                viewModel.monitorSex1=""
                                viewModel.monitorAge1=""
                                viewModel.numberEarlyWarning1=0
                                binding.layoutMonitorInterface1.scanCodeLayout.visibility= View.VISIBLE
                                binding.layoutMonitorInterface1.bloodDonationInfoLayout.visibility= View.GONE
                                binding.layoutMonitorInterface1.tvScanCodeNum.text=""
                                binding.layoutMonitorInterface1.tvPersonInfo.text="个人信息"
                                viewModel.bpList1.clear()
                                adapter1.notifyDataSetChanged()
                            }
                            if (viewModel.upInfo==2){
                                stopMonitorFlag2=0
                                viewModel.excelId2=""
                                viewModel.filePathTwo=""
                                viewModel.monitorCode2=""
                                viewModel.monitorName2=""
                                viewModel.monitorSex2=""
                                viewModel.monitorAge2=""
                                viewModel.numberEarlyWarning2=0
                                binding.layoutMonitorInterface2.scanCodeLayout.visibility=View.VISIBLE
                                binding.layoutMonitorInterface2.bloodDonationInfoLayout.visibility=View.GONE
                                binding.layoutMonitorInterface2.tvScanCodeNum.text=""
                                binding.layoutMonitorInterface2.tvPersonInfo.text="个人信息"
                                viewModel.bpList2.clear()
                                adapter2.notifyDataSetChanged()
                            }
                        })
            }
        })

        viewModel.dataMsg.observe(this, androidx.lifecycle.Observer {
            loadProgressDialog.dismiss()
            if (it=="1"){
                    lifecycleScope.launch(Dispatchers.IO) {
                        Log.e("zsy","${viewModel.monitorCode1}")
                        viewModel.insertRecord(
                            MonitorRecordEntity(bloodDonationCode=viewModel.monitorCode1,
                                name=viewModel.monitorName1,sex=viewModel.monitorSex1,
                                warningTimes=viewModel.numberEarlyWarning1,dateStr=viewModel.sdfFile.format(Date()),
                                fileAddress=viewModel.filePath)
                        )
                        withContext(Dispatchers.Main){
                            stopMonitorFlag1=0
                            viewModel.excelId1=""
                            viewModel.filePath=""
                            viewModel.monitorCode1=""
                            viewModel.monitorName1=""
                            viewModel.monitorSex1=""
                            viewModel.monitorAge1=""
                            viewModel.numberEarlyWarning1=0
                            binding.layoutMonitorInterface1.scanCodeLayout.visibility= View.VISIBLE
                            binding.layoutMonitorInterface1.bloodDonationInfoLayout.visibility= View.GONE
                            binding.layoutMonitorInterface1.tvScanCodeNum.text=""
                            binding.layoutMonitorInterface1.tvPersonInfo.text="个人信息"
                            viewModel.bpList1.clear()
                            adapter1.notifyDataSetChanged()
                        }
                    }

            }else if (it=="2") {
                lifecycleScope.launch(Dispatchers.IO) {
                    Log.e("zsy","${viewModel.monitorCode2}")
                    viewModel.insertRecord(
                        MonitorRecordEntity(bloodDonationCode=viewModel.monitorCode2,
                            name=viewModel.monitorName2,sex=viewModel.monitorSex2,
                            warningTimes=viewModel.numberEarlyWarning2,
                            dateStr=viewModel.sdfFile.format(Date()),
                            fileAddress=viewModel.filePathTwo))
                    withContext(Dispatchers.Main){
                        stopMonitorFlag2=0
                        viewModel.excelId2=""
                        viewModel.filePathTwo=""
                        viewModel.monitorCode2=""
                        viewModel.monitorName2=""
                        viewModel.monitorSex2=""
                        viewModel.monitorAge2=""
                        viewModel.numberEarlyWarning2=0
                        binding.layoutMonitorInterface2.scanCodeLayout.visibility=View.VISIBLE
                        binding.layoutMonitorInterface2.bloodDonationInfoLayout.visibility=View.GONE
                        binding.layoutMonitorInterface2.tvScanCodeNum.text=""
                        binding.layoutMonitorInterface2.tvPersonInfo.text="个人信息"
                        viewModel.bpList2.clear()
                        adapter2.notifyDataSetChanged()
                    }
                }
            }  else {
                if (it.contains("上传失败")){
//                    Toast.makeText(requireContext(),"${it}",Toast.LENGTH_LONG).show()
                    DialogUploadFailedUtil.showCustomDialogWithCountdown(
                        requireActivity(),
                        DialogUploadFailedUtil.DialogType.INFO,
                        onPositiveButtonClick = {
                            // 确定按钮点击事件的逻辑
                            if (viewModel.upFileFail==1){
                                stopMonitorFlag1=0
                                val excelFile = File(viewModel.filePath)
                                Log.e("zsy","数据已成功导出到Excel文件 ${excelFile.length()}")
                                if (excelFile.exists()) {
                                    Log.e("zsy","文件是否存在=${excelFile.exists()}")
                                    viewModel.uploadFile(excelFile,1)
                                }
                                viewModel.excelListDataTemp.clear()
                                binding.layoutMonitorInterface1.tvMonitoringControl1.text="开始监测"
                            }

                            if (viewModel.upFileFail==2){
                                stopMonitorFlag2=0
                                val excelFile = File(viewModel.filePathTwo)
                                Log.e("zsy","数据已成功导出到Excel文件 ${excelFile.length()}")
                                if (excelFile.exists()) {
                                    Log.e("zsy","文件是否存在=${excelFile.exists()}")
                                    viewModel.uploadFile(excelFile,2)
                                }
                                viewModel.excelListDataTempTwo.clear()
                                binding.layoutMonitorInterface2.tvMonitoringControl1.text="开始监测"
                            }
                        },
                        onNegativeButtonClick = {
                            // 取消按钮点击事件的逻辑
                            if (viewModel.upFileFail==1){
                                lifecycleScope.launch(Dispatchers.IO) {
                                    Log.e("zsy","${viewModel.monitorCode1}")
                                    viewModel.insertRecord(
                                        MonitorRecordEntity(bloodDonationCode=viewModel.monitorCode1,
                                            name=viewModel.monitorName1,sex=viewModel.monitorSex1,
                                            warningTimes=viewModel.numberEarlyWarning1,dateStr=viewModel.sdfFile.format(Date()),
                                            fileAddress=viewModel.filePath))
                                    withContext(Dispatchers.Main){
                                        MyApp.stopMonitorFlag1 =0
                                        viewModel.filePath=""
                                        viewModel.monitorCode1=""
                                        viewModel.monitorName1=""
                                        viewModel.monitorSex1=""
                                        viewModel.monitorAge1=""
                                        viewModel.numberEarlyWarning1=0
                                        binding.layoutMonitorInterface1.scanCodeLayout.visibility=View.VISIBLE
                                        binding.layoutMonitorInterface1.bloodDonationInfoLayout.visibility=View.GONE
                                        binding.layoutMonitorInterface1.tvScanCodeNum.text=""
                                        binding.layoutMonitorInterface1.tvPersonInfo.text="个人信息"
                                        viewModel.bpList1.clear()
                                        adapter1.notifyDataSetChanged()
                                    }
                                }
                            }
                            if (viewModel.upFileFail==2){
                                lifecycleScope.launch(Dispatchers.IO) {
                                    Log.e("zsy","${viewModel.monitorCode2}")
                                    viewModel.insertRecord(
                                        MonitorRecordEntity(bloodDonationCode=viewModel.monitorCode2,
                                            name=viewModel.monitorName2,sex=viewModel.monitorSex2,
                                            warningTimes=viewModel.numberEarlyWarning2,
                                            dateStr=viewModel.sdfFile.format(Date()),
                                            fileAddress=viewModel.filePathTwo))
                                    withContext(Dispatchers.Main){
                                        stopMonitorFlag2=0
                                        viewModel.filePathTwo=""
                                        viewModel.monitorCode2=""
                                        viewModel.monitorName2=""
                                        viewModel.monitorSex2=""
                                        viewModel.monitorAge2=""
                                        viewModel.numberEarlyWarning2=0
                                        binding.layoutMonitorInterface2.scanCodeLayout.visibility=View.VISIBLE
                                        binding.layoutMonitorInterface2.bloodDonationInfoLayout.visibility=View.GONE
                                        binding.layoutMonitorInterface2.tvScanCodeNum.text=""
                                        binding.layoutMonitorInterface2.tvPersonInfo.text="个人信息"
                                        viewModel.bpList2.clear()
                                        adapter2.notifyDataSetChanged()
                                    }
                                }
                            }
                        }
                    )
                }
            }
        })

        LiveEventBus.get("DataNotify", MsgBleData::class.java).observe(this, androidx.lifecycle.Observer {
            when(it.type){
                1->{// 左侧血压计数据
                    if (it.bleData!!.contains("aa55430701") && viewModel.bpTempData1.isEmpty()){
                        Log.e("zsy","血压接收=${viewModel.bpTempData1}    计次=${viewModel.bpTempDataCount1}")
                        viewModel.bpTempData1=it.bleData!!
                        val sdf = SimpleDateFormat("HH:mm:ss")
                        val timeStr = sdf.format(Date())
                        var bpStatus = "0"
                        var hp=it.bleData!!.substring(12, 14).toInt(16)
                        var lp=it.bleData!!.substring(16, 18).toInt(16)

                        bpStatus = if (hp in 90..139 && lp in 60..89 ) {
                            "0"
                        } else {
                            if (hp > 139 || lp > 89) {
                                "1"
                            } else {
                                "2"
                            }
                        }
                        viewModel.bpData1 = "${hp}/${lp}"
                        viewModel.bpList1.add(BpDataBean(time = timeStr, h_pressure = "${hp}", l_pressure = "${lp}", bloodPressureStatus = bpStatus))
                        adapter1.notifyDataSetChanged()
                        countTempBp1()
                        // 更新上次添加数据的时间为当前时间
                        binding.layoutMonitorInterface1.tvStartBp.text = "开始测量"

                    }
                }
                2->{// 左侧 血氧 计数据
                    if (it.bleData!!.length>=4){
                        addData1(it.bleData!!.subSequence(0,2).toString().toInt(16), it.bleData!!.subSequence(2,4).toString().toInt(16))
                        if (viewModel.monitorCode1.isNotEmpty() && viewModel.filePath.isNotEmpty()&& stopMonitorFlag1==0){
                            binding.layoutMonitorInterface1.tvMonitoringControl1.text="停止监测"
                            var pr=it.bleData!!.subSequence(2,4).toString().toInt(16)
                            var spo=it.bleData!!.subSequence(0,2).toString().toInt(16)
                            Log.e("zsy","pr===${pr}  spo===${spo}")
                            if (spo in 80..93 && pr!=0){
//                                if (spo <93){
                                viewModel.alertStatusRecordSpo1="血氧偏低"
                                viewModel.alertStatusValueSpo1="10"
                            }else{
                                viewModel.alertStatusRecordSpo1=""
                                viewModel.alertStatusValueSpo1=""
                            }
                            if (pr !in 60..100 && pr!=0){
                                if (pr<60){
                                    viewModel.alertStatusRecordPr1="脉搏偏低"
                                    viewModel.alertStatusValuePr1="20"
                                }else{
                                    viewModel.alertStatusRecordPr1="脉搏偏高"
                                    viewModel.alertStatusValuePr1="20"
                                }
                            }else{
                                viewModel.alertStatusRecordPr1=""
                                viewModel.alertStatusValuePr1=""
                            }
//                            if (spo in 80..95 && pr!=0){
////
//                                viewModel.alertStatusRecordSpo1="血氧偏低"
//                                viewModel.alertStatusValueSpo1="10"
//                            }else{
//                                viewModel.alertStatusRecordSpo1=""
//                                viewModel.alertStatusValueSpo1=""
//                            }
//                            if (pr in 60..85 && pr!=0){
//                                if (pr<60){
//                                    viewModel.alertStatusRecordPr1="脉搏偏低"
//                                    viewModel.alertStatusValuePr1="20"
//                                }else{
//                                    viewModel.alertStatusRecordPr1="脉搏偏高"
//                                    viewModel.alertStatusValuePr1="20"
//                                }
//                            }else{
//                                viewModel.alertStatusRecordPr1=""
//                                viewModel.alertStatusValuePr1=""
//                            }

                            if (viewModel.bpData1.isNotEmpty()){
                                val bpSplit = viewModel.bpData1.split("/")
                                if (bpSplit[1].toInt() > 89 || bpSplit[0].toInt() > 139) {
                                    viewModel.alertStatusRecordBp1="血压偏高"
                                    viewModel.alertStatusValueBp1="30"
                                } else  if (bpSplit[1].toInt() < 60 || bpSplit[0].toInt() < 90){
                                    viewModel.alertStatusRecordBp1="血压偏低"
                                    viewModel.alertStatusValueBp1="30"
                                }
                            }else{
                                viewModel.alertStatusRecordBp1=""
                                viewModel.alertStatusValueBp1=""
                            }
                            var earlyWarningTime=""
                            if (viewModel.alertStatusRecordSpo1.isNotEmpty() || viewModel.alertStatusRecordPr1.isNotEmpty() || viewModel.alertStatusRecordBp1.isNotEmpty()){
                                earlyWarningTime=viewModel.sdfEarlyWarning.format(Date())
                                viewModel.numberEarlyWarning1+=1
                            }

                            Log.e("zsy","${viewModel.alertStatusRecordSpo1}      ${viewModel.alertStatusRecordPr1}${viewModel.alertStatusValuePr1}         ${viewModel.alertStatusRecordBp1}     ${alarmRecord1.endsWith("开始")} ${FileUtils.isFirstLineEndsWith(alarmRecord1,"开始")}")

                            if (earlyWarningTime.isNotEmpty() &&
                                (binding.layoutMonitorInterface1.tvEarlyWarningRecord.text.toString().isEmpty() || alarmRecord1.endsWith("结束"))){
                                Log.e("zsy","${earlyWarningTime} 异常信息开始")
                                alarmRecord1="${alarmRecord1}\n${viewModel.monitorCode1}:异常状态:\n${viewModel.alertStatusRecordSpo1}${viewModel.alertStatusRecordPr1}${viewModel.alertStatusRecordBp1}:${viewModel.sdfDateTime.format(Date())}:开始"
                                binding.layoutMonitorInterface1.tvEarlyWarningRecord.text="${alarmRecord1}"

                                viewModel.exception(1,
                                    viewModel.alertStatusValueSpo1,viewModel.alertStatusValuePr1,viewModel.alertStatusValueBp1,
                                    "10",
                                    viewModel.alertStatusRecordSpo1,viewModel.alertStatusRecordPr1,viewModel.alertStatusRecordBp1,
                                    viewModel.sopVerification(spo),viewModel.pulseVerification(pr),if (viewModel.bpData1.isNotEmpty()) viewModel.bpVerification(viewModel.bpData1) else "")

                            }else if (viewModel.alertStatusRecordSpo1.isEmpty() && viewModel.alertStatusRecordPr1.isEmpty() && viewModel.alertStatusRecordBp1.isEmpty() && alarmRecord1.endsWith("开始")){
                                Log.e("zsy","异常信息结束")
                                alarmRecord1="${alarmRecord1}\n${viewModel.monitorCode1}:异常状态:\n${viewModel.sdfDateTime.format(Date())}:结束"
                                binding.layoutMonitorInterface1.tvEarlyWarningRecord.text="${alarmRecord1}"
                                viewModel.exception(1,"", "","","0", "","","", "","","")
                            }

                            viewModel.excelListData.add(MonitorRecordsBean(bloodDonationCode="${viewModel.monitorCode1}",
                                name="${viewModel.monitorName1}",
                                sex="${viewModel.monitorSex1}",
                                age="${viewModel.monitorAge1}",
                                bloodOxygen="${spo}",
                                bloodPressure="${viewModel.bpData1}",
                                pulse="${pr}",
                                temperature="",
                                monitorTime="${viewModel.sdfEarlyWarning.format(Date())}",
                                earlyWarningTime="${earlyWarningTime}",
                                reasonsEarlyWarning="${viewModel.alertStatusRecordSpo1}${viewModel.alertStatusRecordPr1}${viewModel.alertStatusRecordBp1}",
                                dataAcquisitionDeviceNumber=""))
                            viewModel.bpData1=""
                            Log.e("zsy","数据个数=${viewModel.excelListData.size}")
                            if (viewModel.excelListData.size>=50){
                                viewModel.excelListDataTemp.addAll(viewModel.excelListData)
                                lifecycleScope.launch(Dispatchers.IO){
                                    viewModel.excelListData.clear()
                                    Log.e("zsy","现在这里有几个数据${viewModel.excelListDataTemp.size}")
                                    val result = excelService.bloodCollectExportExcel1(viewModel.excelListDataTemp, viewModel.headList, viewModel.filePath)
                                    withContext(Dispatchers.Main){
                                        if (result) {
                                            // 可以在这里添加一些提示信息，比如Toast提示导出成功等
                                            Log.e("zsy","数据已成功导出到Excel文件")
                                            viewModel.excelListDataTemp.clear()
                                        } else {
                                            // 同样可以添加提示信息告知导出失败
                                            Log.e("zsy","数据导出失败，请检查相关设置")
                                        }
                                    }
                                }
                            }
                        }else{
                            binding.layoutMonitorInterface1.tvMonitoringControl1.text="开始监测"
                        }
                    }
                }
                3->{
                    binding.layoutMonitorInterface1.tvSpoConnectStatus.text="已连接 ${O2RingName}"
                    loadProgressDialog.dismiss()
                    viewModel.o2ringConnectStatus1=1
                }
                4->{
                    if (it.bleData!!.contains("血氧")){
                        viewModel.o2ringConnectStatus1=0
                    }
                    binding.layoutMonitorInterface1.tvSpoConnectStatus.text="未连接 ${O2RingName}"
                    loadProgressDialog.dismiss()
                    Toast.makeText(requireContext(),"${it.bleData}",Toast.LENGTH_LONG).show()
                }
                5->{
                    binding.layoutMonitorInterface1.tvBpConnectStatus.text="已连接 ${BPName}"
                    loadProgressDialog.dismiss()
//                    handler.postDelayed(bp,10000)
                    viewModel.bPConnectStatus1=true
                    LiveEventBus.get("receiveCmd2",SendCmd::class.java).postDelay(SendCmd(type = 1, cmd = BPStartCmd),1500)
                    binding.layoutMonitorInterface1.tvStartBp.text="停止测量"
                }
                6->{
                    binding.layoutMonitorInterface1.tvBpConnectStatus.text="未连接 ${BPName}"
                    loadProgressDialog.dismiss()
                    viewModel.bPConnectStatus1=false
                    ToastUtils.show(it.bleData)
                    binding.layoutMonitorInterface1.tvStartBp.text="开始测量"
                }
                8->{
                    Toast.makeText(requireContext(),"${it.bleData}",Toast.LENGTH_LONG).show()
                }
            }
        })

        LiveEventBus.get("DataNotifyTwo", MsgBleData::class.java).observe(this, androidx.lifecycle.Observer {
            when(it.type){
                1->{// 左侧血压计数据
                    if (it.bleData!!.contains("aa55430701") && viewModel.bpTempData2.isEmpty()){
                        viewModel.bpTempData2=it.bleData!!
                        val sdf = SimpleDateFormat("HH:mm:ss")
                        val timeStr = sdf.format(Date())
                        var bpStatus = "0"
                        var hp=it.bleData!!.substring(12, 14).toInt(16)
                        var lp=it.bleData!!.substring(16, 18).toInt(16)

                        bpStatus = if (hp in 90..139 && lp in 60..89 ) { "0"
                        } else {
                            if (hp > 139 || lp > 89) {
                                "1"
                            } else {
                                "2"
                            }
                        }
                        viewModel.bpData2 = "${hp}/${lp}"
                        viewModel.bpList2.add(BpDataBean(time = timeStr, h_pressure = "${hp}", l_pressure = "${lp}", bloodPressureStatus = bpStatus))
                        adapter2.notifyDataSetChanged()
                        countTempBp2()
                        // 更新上次添加数据的时间为当前时间
                        binding.layoutMonitorInterface2.tvStartBp.text = "开始测量"

                    }
                }
                2->{// 左侧 血氧 计数据
                    if (it.bleData!!.length>=4){
                        addData2(it.bleData!!.subSequence(0,2).toString().toInt(16), it.bleData!!.subSequence(2,4).toString().toInt(16))
                        if (viewModel.monitorCode2.isNotEmpty() && viewModel.filePathTwo.isNotEmpty() && stopMonitorFlag2==0){
                            binding.layoutMonitorInterface2.tvMonitoringControl1.text="停止监测"
                            var pr=it.bleData!!.subSequence(2,4).toString().toInt(16)
                            var spo=it.bleData!!.subSequence(0,2).toString().toInt(16)
                            if (spo in 80..93 && pr!=0){
                                viewModel.alertStatusRecordSpo2="血氧偏低"
                                viewModel.alertStatusValueSpo2="10"
                            }else{
                                viewModel.alertStatusRecordSpo2=""
                                viewModel.alertStatusValueSpo2=""
                            }
                            if (pr !in 60..100 && pr!=0){
                                if (pr<60){
                                    viewModel.alertStatusRecordPr2="脉搏偏低"
                                    viewModel.alertStatusValuePr2="20"
                                }else{
                                    viewModel.alertStatusRecordPr2="脉搏偏高"
                                    viewModel.alertStatusValuePr2="20"
                                }
                            }else{
                                viewModel.alertStatusRecordPr2=""
                                viewModel.alertStatusValuePr2=""
                            }
                            if (viewModel.bpData2.isNotEmpty()){
                                val bpSplit = viewModel.bpData2.split("/")
                                if (bpSplit[1].toInt() > 89 || bpSplit[0].toInt() > 139) {
                                    viewModel.alertStatusRecordBp2="血压偏高"
                                    viewModel.alertStatusValueBp2="30"
                                } else  if (bpSplit[1].toInt() < 60 || bpSplit[0].toInt() < 90){
                                    viewModel.alertStatusRecordBp2="血压偏低"
                                    viewModel.alertStatusValueBp2="30"
                                }
                            }else{
                                viewModel.alertStatusRecordBp2=""
                                viewModel.alertStatusValueBp2=""
                            }
                            var earlyWarningTime=""
                            if (viewModel.alertStatusRecordSpo2.isNotEmpty() || viewModel.alertStatusRecordPr2.isNotEmpty() || viewModel.alertStatusRecordBp2.isNotEmpty()){
                                earlyWarningTime=viewModel.sdfEarlyWarning.format(Date())
                                viewModel.numberEarlyWarning2+=1
                            }


                            if (earlyWarningTime.isNotEmpty() && (binding.layoutMonitorInterface2.tvEarlyWarningRecord.text.toString().isEmpty() || alarmRecord2.endsWith("结束"))){
                                Log.e("zsy","异常信息开始")
                                alarmRecord2="${viewModel.monitorCode2}:异常状态:\n${viewModel.alertStatusRecordSpo2}${viewModel.alertStatusRecordPr2}${viewModel.alertStatusRecordBp2}:${viewModel.sdfDateTime.format(Date())}:开始\n${alarmRecord2}"
                                binding.layoutMonitorInterface2.tvEarlyWarningRecord.text="${alarmRecord2}"
                                viewModel.exception(2,viewModel.alertStatusValueSpo2,viewModel.alertStatusValuePr2,viewModel.alertStatusValueBp2,
                                    "10",
                                    viewModel.alertStatusRecordSpo2,viewModel.alertStatusRecordPr2,viewModel.alertStatusRecordBp2,
                                    viewModel.sopVerification(spo),viewModel.pulseVerification(pr),if (viewModel.bpData2.isNotEmpty()) viewModel.bpVerification(viewModel.bpData2) else "")
                            }else if (viewModel.alertStatusRecordSpo2.isEmpty() && viewModel.alertStatusRecordPr2.isEmpty() && viewModel.alertStatusRecordBp2.isEmpty() && alarmRecord2.endsWith("开始")){
                                Log.e("zsy","异常信息结束")
                                alarmRecord2="${alarmRecord2}\n${viewModel.monitorCode2}:异常状态:\n${viewModel.sdfDateTime.format(Date())}:结束"
                                binding.layoutMonitorInterface2.tvEarlyWarningRecord.text="${alarmRecord2}"
                                viewModel.exception(2,"", "","","0", "","","", "","","")
                            }

                            viewModel.excelListDataTwo.add(MonitorRecordsBean(
                                bloodDonationCode="${viewModel.monitorCode2}",
                                name="${viewModel.monitorName2}",
                                sex="${viewModel.monitorSex2}",
                                age="${viewModel.monitorAge2}",
                                bloodOxygen="${spo}",
                                bloodPressure="${viewModel.bpData2}",
                                pulse="${pr}",
                                temperature="",
                                monitorTime="${viewModel.sdfEarlyWarning.format(Date())}",
                                earlyWarningTime="${earlyWarningTime}",
                                reasonsEarlyWarning="${viewModel.alertStatusRecordSpo2}${viewModel.alertStatusRecordPr2}${viewModel.alertStatusRecordBp2}",
                                dataAcquisitionDeviceNumber=""))
                            viewModel.bpData2=""
                            Log.e("zsy","数据个数=${viewModel.excelListDataTwo.size}")
                            if (viewModel.excelListDataTwo.size>=50){
                                viewModel.excelListDataTempTwo.addAll(viewModel.excelListDataTwo)
                                lifecycleScope.launch(Dispatchers.IO){
                                    viewModel.excelListDataTwo.clear()
                                    Log.e("zsy","现在这里有几个数据${viewModel.excelListDataTempTwo.size}")
                                    val result = excelService.bloodCollectExportExcel2(viewModel.excelListDataTempTwo, viewModel.headList, viewModel.filePathTwo)
                                    withContext(Dispatchers.Main){
                                        if (result) {
                                            // 可以在这里添加一些提示信息，比如Toast提示导出成功等
                                            Log.e("zsy","数据已成功导出到Excel文件")
                                            viewModel.excelListDataTempTwo.clear()
                                        } else {
                                            // 同样可以添加提示信息告知导出失败
                                            Log.e("zsy","数据导出失败，请检查相关设置")
                                        }
                                    }
                                }
                            }
                        }else{
                            binding.layoutMonitorInterface2.tvMonitoringControl1.text="开始监测"
                        }
                    }
                }
                3->{
                    binding.layoutMonitorInterface2.tvSpoConnectStatus.text="已连接 ${O2RingNameRight}"
                    loadProgressDialog.dismiss()
                    viewModel.o2ringConnectStatus2=1
                }
                4->{
                    if (it.bleData!!.contains("血氧")){
                        viewModel.o2ringConnectStatus2=0
                    }
                    loadProgressDialog.dismiss()
//                    ToastUtils.show(it.bleData)
                    binding.layoutMonitorInterface2.tvSpoConnectStatus.text="未连接 ${O2RingNameRight}"
//                    binding.layoutMonitorInterface2.tvStartBp.text="开始连接"
                    Toast.makeText(requireContext(),"${it.bleData}",Toast.LENGTH_LONG).show()
                }
                5->{
                    binding.layoutMonitorInterface2.tvBpConnectStatus.text="已连接 ${BPNameRight}"
                    loadProgressDialog.dismiss()
//                    handler.postDelayed(bp2,10000)
                    viewModel.bPConnectStatus2=true
                    LiveEventBus.get("receiveCmdTwo2",SendCmd::class.java).postDelay(SendCmd(type = 1, cmd = BPStartCmd),1500)
                    binding.layoutMonitorInterface2.tvStartBp.text="停止测量"
                }
                6->{
                    binding.layoutMonitorInterface2.tvBpConnectStatus.text="未连接 ${BPNameRight}"
                    loadProgressDialog.dismiss()
                    viewModel.bPConnectStatus2=false
                    ToastUtils.show(it.bleData)
                    binding.layoutMonitorInterface2.tvStartBp.text="开始测量"
                }
                8->{
                    Toast.makeText(requireContext(),"${it.bleData}",Toast.LENGTH_LONG).show()
                }
            }

        })

    }


    fun initChart1() {
        // 启用触摸和拖动
        binding.layoutMonitorInterface1.lineChart1.setTouchEnabled(false)
        binding.layoutMonitorInterface1.lineChart1.setDragEnabled(false)
        binding.layoutMonitorInterface1.lineChart1.setScaleEnabled(false)
        binding.layoutMonitorInterface1.lineChart1.setNoDataText("暂无数据")

        // 图例设置
        val legend: Legend = binding.layoutMonitorInterface1.lineChart1.getLegend()
        legend.isEnabled = false
        legend.form = Legend.LegendForm.LINE
        legend.textColor = Color.BLACK
        // X轴设置
        val xAxis: XAxis = binding.layoutMonitorInterface1.lineChart1.getXAxis()
        xAxis.position = XAxis.XAxisPosition.BOTTOM
        xAxis.textColor = Color.BLACK
        // 设置X轴的最小和最大值以匹配数据点
        xAxis.axisMaximum = (maxVisibleDataPoints - 1).toFloat()
        xAxis.axisMinimum = 0f
        xAxis.setDrawGridLines(false)
        xAxis.granularity = 1f // 设置粒度为1，确保标签逐个显示
        xAxis.setLabelCount(maxVisibleDataPoints, true) // 设置X轴标签数量，与可见数据点数相同
        xAxis.setDrawAxisLine(true) // 保留X轴的轴线（顶部的那条线是X轴的轴线）
        xAxis.valueFormatter = object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                val index = value.toInt()
                return if (index >= 0 && index < viewModel.timeStamps1.size) {
                    viewModel.timeStamps1[index]
                } else ""
            }
        }
        xAxis.textSize = 6f
        // 左侧Y轴设置（血氧）
        val leftAxis: YAxis = binding.layoutMonitorInterface1.lineChart1.axisLeft
        leftAxis.axisMaximum = 100f // 血氧最大值
        leftAxis.axisMinimum = 85f // 血氧最小值
        leftAxis.granularity = 5f // 血氧刻度间隔
        leftAxis.textColor = Color.BLACK
        leftAxis.textSize=8.0f
        leftAxis.setDrawGridLines(false) // 显示左侧的网格线
        leftAxis.setDrawAxisLine(true) // 保留左侧的轴线（实线）
        leftAxis.enableGridDashedLine(10f, 10f, 0f) // 使用 DashPathEffect 实现虚线效果
        // 自定义电压刻度格式
        leftAxis.valueFormatter = viewModel.OxygenFormatter()
        // 右侧Y轴设置（脉搏）
        val rightAxis: YAxis = binding.layoutMonitorInterface1.lineChart1.getAxisRight()
        rightAxis.axisMaximum = 210f // 脉搏最大值
        rightAxis.axisMinimum = 30f // 脉搏最小值
        rightAxis.granularity = 30f // 脉搏刻度间隔
        rightAxis.textColor = Color.BLACK
        rightAxis.textSize=8.0f
        rightAxis.setDrawGridLines(true) // 显示右侧的网格线
        rightAxis.setDrawAxisLine(true) // 保留右侧的轴线（实线）
        rightAxis.enableGridDashedLine(5f, 5f, 0f) // 使用 DashPathEffect 实现虚线效果
        // 自定义电流刻度格式
        rightAxis.valueFormatter = viewModel.HeartFormatter()
        // 隐藏描述标签
         binding.layoutMonitorInterface1.lineChart1.description.isEnabled = false
    }

    fun initChart2() {
        // 启用触摸和拖动
        binding.layoutMonitorInterface2.lineChart1.setTouchEnabled(false)
        binding.layoutMonitorInterface2.lineChart1.setDragEnabled(false)
        binding.layoutMonitorInterface2.lineChart1.setScaleEnabled(false)
        binding.layoutMonitorInterface2.lineChart1.setNoDataText("暂无数据")
        // 图例设置
        val legend: Legend = binding.layoutMonitorInterface2.lineChart1.getLegend()
        legend.isEnabled = false
        legend.form = Legend.LegendForm.LINE
        legend.textColor = Color.BLACK
        // X轴设置
        val xAxis: XAxis = binding.layoutMonitorInterface2.lineChart1.getXAxis()
        xAxis.position = XAxis.XAxisPosition.BOTTOM
        xAxis.textColor = Color.BLACK
        // 设置X轴的最小和最大值以匹配数据点
        xAxis.axisMaximum = (maxVisibleDataPoints - 1).toFloat()
        xAxis.axisMinimum = 0f
        xAxis.setDrawGridLines(false)
        xAxis.granularity = 1f // 设置粒度为1，确保标签逐个显示
        xAxis.setLabelCount(maxVisibleDataPoints, true) // 设置X轴标签数量，与可见数据点数相同
        xAxis.setDrawAxisLine(true) // 保留X轴的轴线（顶部的那条线是X轴的轴线）
        xAxis.valueFormatter = object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                val index = value.toInt()
                return if (index >= 0 && index < viewModel.timeStamps2.size) {
                    viewModel.timeStamps2[index]
                } else ""
            }
        }
        xAxis.textSize = 6f
        // 左侧Y轴设置（血氧）
        val leftAxis: YAxis = binding.layoutMonitorInterface2.lineChart1.axisLeft
        leftAxis.axisMaximum = 100f // 血氧最大值
        leftAxis.axisMinimum = 85f // 血氧最小值
        leftAxis.granularity = 5f // 血氧刻度间隔
        leftAxis.textColor = Color.BLACK
        leftAxis.textSize=8.0f
        leftAxis.setDrawGridLines(false) // 显示左侧的网格线
        leftAxis.setDrawAxisLine(true) // 保留左侧的轴线（实线）
        leftAxis.enableGridDashedLine(10f, 10f, 0f) // 使用 DashPathEffect 实现虚线效果
        // 自定义电压刻度格式
        leftAxis.valueFormatter = viewModel.OxygenFormatter()
        // 右侧Y轴设置（脉搏）
        val rightAxis: YAxis = binding.layoutMonitorInterface2.lineChart1.getAxisRight()
        rightAxis.axisMaximum = 210f // 脉搏最大值
        rightAxis.axisMinimum = 30f // 脉搏最小值
        rightAxis.granularity = 30f // 脉搏刻度间隔
        rightAxis.textColor = Color.BLACK
        rightAxis.textSize=8.0f
        rightAxis.setDrawGridLines(true) // 显示右侧的网格线
        rightAxis.setDrawAxisLine(true) // 保留右侧的轴线（实线）
        rightAxis.enableGridDashedLine(5f, 5f, 0f) // 使用 DashPathEffect 实现虚线效果
        // 自定义电流刻度格式
        rightAxis.valueFormatter = viewModel.HeartFormatter()
        // 隐藏描述标签
        binding.layoutMonitorInterface2.lineChart1.description.isEnabled = false
    }

    // 添加数据的方法
     fun addData1(oxygen: Int, pulse: Int) {
        val currentTimeMillis = System.currentTimeMillis()
        val date = Date(currentTimeMillis)
        if (viewModel.oxygenData.size >= maxVisibleDataPoints) {
            viewModel.oxygenData.removeAt(0)
            viewModel.pulseData.removeAt(0)
            viewModel.timeStamps1.removeAt(0)
            // 调整剩余数据的X轴位置
            for (i in viewModel.oxygenData.indices) {
                viewModel.oxygenData[i].x = i.toFloat()
                viewModel.pulseData[i].x = i.toFloat()
            }
        }
        // 添加新数据点
        viewModel.oxygenData.add(Entry(viewModel.oxygenData.size.toFloat(), oxygen.toFloat()))
        viewModel.pulseData.add(Entry(viewModel.pulseData.size.toFloat(), pulse.toFloat()))
        viewModel.timeStamps1.add(dateFormat.format(date))
        // 更新图表数据
        val oxygenDataSet = createOxygenLineDataSet1(viewModel.oxygenData, "血氧(%)", Color.parseColor("#F82C2C"))
        val heartDataSet = createPulseLineDataSet1(viewModel.pulseData, "脉搏(次/分)", Color.parseColor("#0BAB10"))
        heartDataSet.axisDependency = YAxis.AxisDependency.RIGHT
        val lineData = LineData(oxygenDataSet, heartDataSet)
        binding.layoutMonitorInterface1.lineChart1.data = lineData
        binding.layoutMonitorInterface1.lineChart1.invalidate() // 刷新图表
    }

    // 添加数据的方法
    fun addData2(oxygen: Int, pulse: Int) {
        val currentTimeMillis = System.currentTimeMillis()
        val date = Date(currentTimeMillis)
        if (viewModel.oxygenData2.size >= maxVisibleDataPoints) {
            viewModel.oxygenData2.removeAt(0)
            viewModel.pulseData2.removeAt(0)
            viewModel.timeStamps2.removeAt(0)
            // 调整剩余数据的X轴位置
            for (i in viewModel.oxygenData2.indices) {
                viewModel.oxygenData2[i].x = i.toFloat()
                viewModel.pulseData2[i].x = i.toFloat()
            }
        }
        // 添加新数据点
        viewModel.oxygenData2.add(Entry(viewModel.oxygenData2.size.toFloat(), oxygen.toFloat()))
        viewModel.pulseData2.add(Entry(viewModel.pulseData2.size.toFloat(), pulse.toFloat()))
        viewModel.timeStamps2.add(dateFormat.format(date))
        // 更新图表数据
        val oxygenDataSet = createOxygenLineDataSet2(viewModel.oxygenData2, "血氧(%)", Color.parseColor("#F82C2C"))
        val heartDataSet = createPulseLineDataSet2(viewModel.pulseData2, "脉搏(次/分)", Color.parseColor("#0BAB10"))
        heartDataSet.axisDependency = YAxis.AxisDependency.RIGHT
        val lineData = LineData(oxygenDataSet, heartDataSet)
        binding.layoutMonitorInterface2.lineChart1.data = lineData
        binding.layoutMonitorInterface2.lineChart1.invalidate() // 刷新图表
    }

    // 创建数据集的方法
    fun createOxygenLineDataSet1(data: List<Entry>, label: String, color: Int): LineDataSet {
        val lineDataSet = LineDataSet(data, label)
        lineDataSet.color = color
        lineDataSet.lineWidth = 1f
        lineDataSet.setDrawCircles(false)
        lineDataSet.setDrawValues(false)
        lineDataSet.mode=LineDataSet.Mode.CUBIC_BEZIER
        lineDataSet.cubicIntensity = 0.2f
        lineDataSet.setDrawFilled(true)
        lineDataSet.fillFormatter = IFillFormatter { _, _ ->
            binding.layoutMonitorInterface1.lineChart1.axisLeft.axisMinimum
        }
        var drawable = ContextCompat.getDrawable(requireContext(), R.drawable.oxygen_fade_red)
        drawable?.alpha = 100
        lineDataSet.fillDrawable = drawable
        return lineDataSet
    }

    // 创建数据集的方法
    fun createPulseLineDataSet1(data: List<Entry>, label: String, color: Int): LineDataSet {
        val lineDataSet = LineDataSet(data, label)
        lineDataSet.color = color
        lineDataSet.lineWidth = 1f
        lineDataSet.setDrawCircles(false)
        lineDataSet.setDrawValues(false)
        lineDataSet.mode=LineDataSet.Mode.CUBIC_BEZIER
        lineDataSet.cubicIntensity = 0.2f
        lineDataSet.setDrawFilled(true)
        lineDataSet.fillFormatter = IFillFormatter { _, _ ->
            binding.layoutMonitorInterface1.lineChart1.axisRight.axisMinimum
        }
        var drawable = ContextCompat.getDrawable(requireContext(), R.drawable.pulse_fade_red)
        drawable?.alpha = 100
        lineDataSet.fillDrawable = drawable
        return lineDataSet
    }

    // 创建数据集的方法
    fun createOxygenLineDataSet2(data: List<Entry>, label: String, color: Int): LineDataSet {
        val lineDataSet = LineDataSet(data, label)
        lineDataSet.color = color
        lineDataSet.lineWidth = 1f
        lineDataSet.setDrawCircles(false)
        lineDataSet.setDrawValues(false)
        lineDataSet.mode=LineDataSet.Mode.CUBIC_BEZIER
        lineDataSet.cubicIntensity = 0.2f
        lineDataSet.setDrawFilled(true)
        lineDataSet.fillFormatter = IFillFormatter { _, _ ->
            binding.layoutMonitorInterface2.lineChart1.axisLeft.axisMinimum
        }
        var drawable = ContextCompat.getDrawable(requireContext(), R.drawable.oxygen_fade_red)
        drawable?.alpha = 100
        lineDataSet.fillDrawable = drawable
        return lineDataSet
    }

    // 创建数据集的方法
    fun createPulseLineDataSet2(data: List<Entry>, label: String, color: Int): LineDataSet {
        val lineDataSet = LineDataSet(data, label)
        lineDataSet.color = color
        lineDataSet.lineWidth = 1f
        lineDataSet.setDrawCircles(false)
        lineDataSet.setDrawValues(false)
        lineDataSet.mode=LineDataSet.Mode.CUBIC_BEZIER
        lineDataSet.cubicIntensity = 0.2f
        lineDataSet.setDrawFilled(true)
        lineDataSet.fillFormatter = IFillFormatter { _, _ ->
            binding.layoutMonitorInterface2.lineChart1.axisRight.axisMinimum
        }
        var drawable = ContextCompat.getDrawable(requireContext(), R.drawable.pulse_fade_red)
        drawable?.alpha = 100
        lineDataSet.fillDrawable = drawable
        return lineDataSet
    }

    fun  infoFillIn(){
        DialogUtil.showCustomDialogWithCountdown(
            requireActivity(),
            DialogUtil.DialogType.INFO,
            onPositiveButtonClick = {param1, param2, param3 ->
                // 确定按钮点击事件的逻辑
                if (viewModel.scanType==0){
                    viewModel.monitorName1=param1
                    viewModel.monitorAge1=param2
                    viewModel.monitorSex1=if (param3=="1") "男" else "女"
                    binding.layoutMonitorInterface1.tvPersonInfo.text="姓名:${param1}  姓名:${param2}  年龄:${viewModel.monitorSex1}"
                }else{
                    viewModel.monitorName2=param1
                    viewModel.monitorAge2=param2
                    viewModel.monitorSex2=if (param3=="1") "男" else "女"
                    binding.layoutMonitorInterface2.tvPersonInfo.text="姓名:${param1}  姓名:${param2}  年龄:${viewModel.monitorSex2}"
                }
            },
            onNegativeButtonClick = {
                // 取消按钮点击事件的逻辑

            }
        )
    }
    
    val REQUEST_CODE_SCAN = 1002

    private fun startScan() {
        val intent = Intent(requireActivity(), CaptureActivity::class.java)
        startActivityForResult(intent, REQUEST_CODE_SCAN)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                var result=data.extras!!["SCAN_RESULT"].toString()
                Log.e("zsy","${result}")
                if (result.isNotEmpty()){
                    if (viewModel.scanType == 0) {
                        if (result.isNotEmpty()) {
                            viewModel.monitorCode1=result
                            binding.layoutMonitorInterface1.scanCodeLayout.visibility = View.GONE
                            binding.layoutMonitorInterface1.bloodDonationInfoLayout.visibility = View.VISIBLE
                            binding.layoutMonitorInterface1.scanCodeImg.setImageBitmap(result.encodeAsBitmap(750, 140))
                            binding.layoutMonitorInterface1.tvScanCodeNum.text = "$result"
//                            infoFillIn()
                        }
                    } else if (viewModel.scanType == 1) {
                        if (result.isNotEmpty()) {
                            viewModel.monitorCode2=result
                            binding.layoutMonitorInterface2.scanCodeLayout.visibility = View.GONE
                            binding.layoutMonitorInterface2.bloodDonationInfoLayout.visibility = View.VISIBLE
                            binding.layoutMonitorInterface2.scanCodeImg.setImageBitmap(result.encodeAsBitmap(750, 140))
                            binding.layoutMonitorInterface2.tvScanCodeNum.text = "$result"
//                            infoFillIn()
                        }
                    }
                }
              /*  for (key in keys) {
                    Log.e("zsy", "Key: " + key + ", Value: " + data.extras!![key])
                    if (key.equals("SCAN_RESULT")){
                        var result=data.extras!![key].toString()
                    }
                }*/
            }
        }
    }


    override fun onResume() {
        super.onResume()
//        viewModel.bpTempData1="sfafd"
//    countTempBp1()

    }

    fun countTempBp1(){
        lifecycleScope.launch(Dispatchers.IO){
            while ( viewModel.bpTempData1.isNotEmpty()){
                Log.e("zsy","计次=${viewModel.bpTempDataCount1}")
                    viewModel.bpTempDataCount1+=1
                if (viewModel.bpTempDataCount1>=5){
                    viewModel.bpTempData1=""
                    viewModel.bpTempDataCount1=0
                    Log.e("zsy","血样中5次清除后=${viewModel.bpTempData1}     计次=${viewModel.bpTempDataCount1}")
                }
                delay(1000)
            }
            Log.e("zsy","结束运行=${viewModel.bpTempData1}    计次=${viewModel.bpTempDataCount1}")
        }
    }

    fun countTempBp2(){
        lifecycleScope.launch(Dispatchers.IO){
            while ( viewModel.bpTempData2.isNotEmpty()){
                Log.e("zsy","计次=${viewModel.bpTempDataCount1}")
                    viewModel.bpTempDataCount2+=1
                if (viewModel.bpTempDataCount2>=5){
                    viewModel.bpTempData2=""
                    viewModel.bpTempDataCount2=0
                }
                delay(1000)
            }
            Log.e("zsy","结束运行=${viewModel.bpTempData2}    计次=${viewModel.bpTempDataCount2}")
        }
    }

}









